#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/22
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask import Blueprint, request, json, jsonify, g, abort, jsonify
from flask_login import current_user
from flask_httpauth import HTTPBasicAuth
from project.define import app_logger
from project.modules import User


# 应用接口
api = Blueprint(name='api', import_name='project', url_prefix='/api/v2')
# 认证接口
auth_api = HTTPBasicAuth()


@auth_api.verify_password
def verify_password(login_name_or_token, password):
    if login_name_or_token == "":
        return False
    if password == "":
        g.current_user = User.verify_auth_token(login_name_or_token)
        g.token_used = True
        return g.current_user is not None
    u = User.query.filter_by(LoginName=login_name_or_token).first()
    if u:
        if u.verify_password(password):
            g.current_user = u
            g.token_used = False
            return True


@api.before_request
@auth_api.login_required
def before_request_auth():
    """
    访问前校验
    """
    if not g.current_user.is_anonymous and not g.current_user.confirmed:
        return abort(401)
    return True


@api.errorhandler(401)
def auth_error():
    """
    认证错误
    """
    return abort(401)


@api.route('/tokens/', methods=['POST'])
def get_token():
    """
    获取token
    """
    if g.current_user.is_anonymous or g.token_used:
        return abort(403)
    return jsonify({'token': g.current_user.generate_auth_token(expiration=3600),'expiration':3600})


@api.route('/test', methods=['POST'])
def auth_test():
    return jsonify(**{'hello':'world'})